<?php
namespace app\controller;

use app\BaseController;
use Curl\Curl;
use think\Db;
use app\model\Neos;
use app\Request;

class Index extends BaseController
{
    protected $request = null;
    protected $neosM = null;
    protected $getFields = "reference, neo_name, speed, date, is_hazardour";

    public function __construct(Request $request) {
        $this->request = $request;
        $this->neosM = new Neos();
    }

    public function index()
    {
        return json(['hello' => 'world']);      
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    // 近3年的时间切分成7天一对
    public function runCmd() {
        $neosM = $this->neosM;
        $tblCnt = $neosM->getTableCnt();
        if($tblCnt) {
            return json(["Data is exist."]);
        }

        set_time_limit(0);
        $start = strtotime($this->request->param('start_date'));
        $end = strtotime($this->request->param('end_date'));
        $api_key = $this->request->param('api_key');
        
        $d = [];
        while($start < $end) {
            $i = [];
            $i['s'] = date('Y-m-d', $start);
            $start = strtotime(date('Y-m-d', $start)."+ 7 days");
            $i['e'] = date('Y-m-d', $start);
            $start = strtotime(date('Y-m-d', $start)."+ 1 days");
            array_push($d, $i);
        }
    
        foreach($d as $v) {
            echo $this->command($v['s'], $v['e'], $api_key);
            sleep(3);
        }
       
        return json('done');
    }

    public function command($start_date, $end_date, $api_key)
    {
        $neosM = $this->neosM;
        $tblCnt = $neosM->getTableCnt();
        if($tblCnt) {          
            echo "数据库现有数据条数：{$tblCnt}.\n";
        }

        // 调用接口获取数据
        $apiUrl = 'https://api.nasa.gov/neo/rest/v1/feed';

        // $start_date = $this->request->param('start_date');
        // $end_date = $this->request->param('end_date');
        // $api_key = $this->request->param('api_key');
        if(empty($api_key)) {
            $api_key = $this->apiKey;
        }
        $apiParams = array(
            'start_date' => $start_date,
            'end_date' =>  $end_date,
            'api_key' =>  $api_key
        );

        $curl = new Curl();       
        $curl->get($apiUrl, $apiParams);
        if ($curl->error_code) {
            $res = [];            
        } else {
            $res = $curl->response;
        }
        
        if(empty($res)) {
            return 'The data of API is Empty.';
        }
        $res = json_decode($res);

        $data = [];
        // 处理接口数据
        foreach($res->near_earth_objects as $k =>$v1 ) {
            $item = [];
            $item['date'] = $k;                       
            foreach($v1 as $v2) {
                $item['neo_name'] = $v2->name;
                $item['reference'] = $v2->neo_reference_id;
                $item['is_hazardour'] = $v2->is_potentially_hazardous_asteroid ? 1 : 0;
                $item['speed'] = 0;
                if(isset($v2->close_approach_data) && $v2->close_approach_data) {
                    foreach($v2->close_approach_data as $v3) {
                        $item['speed'] = $v3->relative_velocity->kilometers_per_hour;
                    }
                }
                array_push($data, $item); 
            }                     
        }

        $r = $neosM->replace()->insertAll($data);
        $resStr = "Get %d new Data from API with the date from %s to %s.";
        $resStr = sprintf($resStr, $r, $start_date, $end_date);
        echo "新增能数据条数：{$resStr}.\n";
        //return json($r);

    }

    // 获取所有的有危险的行星
    public function hazardous(){
        $field = $this->getFields;
        $neosM = new Neos();
        $d = $neosM->getAsteroids($field , ['is_hazardour' => 1]);
        return json($d);
    }
    // 获取最快的行星
    public function fastest(){
        $is_hazardous = $this->request->param('hazardous');
        $where = ['is_hazardour' => 0];
        if($is_hazardous == 'true') {
            $where = ['is_hazardour' => 1];
        }
        $order = ['speed' => 'desc'];

        $field = $this->getFields;
        $d = $this->neosM->getFastestAsteroid($field, $where, $order);
      
        return json($d);
    }
    // 获取年度最多的行星
    public function bestYear(){
        $is_hazardous = $this->request->param('hazardous');
        $where = ['is_hazardour' => 0];
        if($is_hazardous == 'true') {
            $where = ['is_hazardour' => 1];
        }
        $field = " YEAR(date) as Year, COUNT(DISTINCT reference) as yearCount , is_hazardour";
        $order = ["yearCount" => "desc"];
        $d = $this->neosM->getMostAsteroidOfYear($field, $where, $order);
      
        return json($d);
    }

    // 获取月度最多的行星
    public function bestMonth(){
        $is_hazardous = $this->request->param('hazardous');
        $where = ['is_hazardour' => 0];
        if($is_hazardous == 'true') {
            $where = ['is_hazardour' => 1];
        }
        $field = " Month(date) as Month, COUNT(DISTINCT reference) as MonthCount , is_hazardour";
        $order = ["MonthCount" => "desc"];
        $d = $this->neosM->getMostAsteroidOfYear($field, $where, $order);
      
        return json($d);
    }

}
